<template>
<div id="login">
  <el-card style="margin:0 auto;width:400px;margin-top:100px;">
    <div slot="header">
      <span>登陆</span>
    </div>
    <el-form ref="login" :rules="rules" label-position="left" :model="formLoginData" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formLoginData.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formLoginData.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登陆</el-button>
        <router-link to="/regist">注册</router-link>
      </el-form-item>
    </el-form>
  </el-card>
</div>
</template>

<script>
export default {
  data() {
    return {
      formLoginData: {
        username: "",
        password: ""
      },
      rules: {
        username: {
          required: true,
          message: "用户名必须填写",
          trigger: "blur"
        },
        password: {
          required: true,
          message: "密码必须填写",
          trigger: "blur"
        }
      }
    };
  },
  methods: {
    login() {
      this.$refs.login.validate(valid => {
        if (!valid) {
          return;
        }
        this.$http
          .post("/users/login", this.$qs.stringify(this.formLoginData))
          .then(result => {
            if (result.data.error == 0) {
              this.$router.push('/index/happy');
            } else {
              this.$message.error('用户名或密码错误！');
            }
          });
      });
    }
  }
};
</script>
